package com.lzb.musicplayer.audio;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.media3.common.Player;

import com.lzb.musicplayer.R;
import com.lzb.musicplayer.activity.InfoActivity;
import com.lzb.musicplayer.bean.MusicFile;
import com.lzb.musicplayer.dialog.BottomDialog;
import com.lzb.musicplayer.utils.MusicScannerUtil;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

// AudioPlayerViewInfo.java
public class AudioPlayerViewHome extends LinearLayout
        implements AudioPlayerManager.PlaybackStateListener {

    // 播放控制组件
    private ImageView btnPlay, btnPrev, btnNext, ivPlayer;
    private TextView currentTime, totalTime;
    private SeekBar progressBar;
    private TextView tvPlayer1;
    private TextView tvPlayer2;
    private LinearLayout linearx;
    // 播放管理器引用
    private AudioPlayerManager playerManager;
    private ImageView ivDl;


    public AudioPlayerViewHome(Context context) {
        super(context);
        init(context);
    }

    public AudioPlayerViewHome(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        // 加载布局文件
        inflate(context, R.layout.audio_player_layout, this);
        // 初始化播放管理器
        playerManager = AudioPlayerManager.getInstance(context);
        // 绑定视图组件
        bindViews();
        // 设置控件事件
        setupControls();
        btnPlayType();
    }

    private void bindViews() {
        btnPlay = findViewById(R.id.btn_play);
        btnPrev = findViewById(R.id.btn_prev);
        btnNext = findViewById(R.id.btn_next);
        progressBar = findViewById(R.id.progress_bar);
        currentTime = findViewById(R.id.current_time);
        totalTime = findViewById(R.id.total_time);
        tvPlayer1 = findViewById(R.id.tvPlayer1);
        tvPlayer2 = findViewById(R.id.tvPlayer2);
        ivPlayer = findViewById(R.id.ivPlayer);
        linearx = findViewById(R.id.linearx);
        ivDl = findViewById(R.id.ivDl);
        if (playerManager != null) {
            updateProgressDisplay();
        }
    }

    public void startPlay() {
        playerManager.togglePlayback();
    }
    public void startPlayByPosition(int seek) {
        playerManager.prepareAndPlay(seek);
    }

    private void setupControls() {
        // 播放/暂停按钮
        btnPlay.setOnClickListener(v -> playerManager.togglePlayback());

        // 上一首
        btnPrev.setOnClickListener(v -> playerManager.playPrevious());

        // 下一首
        btnNext.setOnClickListener(v -> next());

        // 进度条拖动监听
        progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    playerManager.seekTo(progress * 1000L);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                playerManager.stopProgressUpdates(); // 拖动时暂停自动更新
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                playerManager.startProgressUpdates(); // 结束拖动恢复更新
            }
        });
        ivPlayer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), InfoActivity.class);
                intent.putExtra("list", (Serializable) playerManager.getList());
                getContext().startActivity(intent);
            }
        }); linearx.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), InfoActivity.class);
                intent.putExtra("list", (Serializable) playerManager.getList());
                getContext().startActivity(intent);
            }
        });
        ivDl.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                BottomDialog bottomDlDialog = new BottomDialog(getContext());
                bottomDlDialog.show();
            }
        });
    }

    public void next() {
        playerManager.playNext();
    }

    // region 生命周期管理
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        // 注册状态监听
        playerManager.addListener(this);

    }
    public void setSj(){
        playerManager.setPlaybackMode(AudioPlayerManager.PlaybackMode.SHUFFLE);
    }
    /*@Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 移除状态监听
        playerManager.removeListener(this);

    }*/
    // endregion

    // region 播放控制方法
    public void setPlayList(List<MusicFile> list, int position) {
        playerManager.play(list, position);
    }
    public void setList(List<MusicFile> list) {
        playerManager.play(list);
    }


    public void pause() {
        playerManager.pause();
    }

    public void clean() {
        playerManager.clean();
    }

    public List<MusicFile> getList() {
        if (playerManager != null) {
            List<MusicFile> list = playerManager.getList();
            return list;
        }
        return null;

    }
    public MusicFile getMusicFile() {
        if (playerManager != null) {
            MusicFile currentTrack = playerManager.getCurrentTrack();
            return currentTrack;
        }
        return null;

    }
    public boolean isPlay() {
        if (playerManager != null) {
            return playerManager.isPlaying();
        }
        return false;

    }


    private void updateProgressDisplay() {
        long position = playerManager.getCurrentPosition();
        long duration = playerManager.getDuration();

        progressBar.setMax((int) (duration / 1000));
        progressBar.setProgress((int) (position / 1000));

        currentTime.setText(formatTime(position));
        totalTime.setText(formatTime(duration));
        if (playerManager.getCurrentTrack() != null) {
            MusicFile musicFile = playerManager.getCurrentTrack();

            if (!TextUtils.isEmpty(musicFile.getTitle())) {
                tvPlayer1.setText(musicFile.getTitle());
            }
            if (!TextUtils.isEmpty(musicFile.getArtist())) {
                tvPlayer2.setText(musicFile.getArtist());
            }
            Bitmap albumCover = MusicScannerUtil.getAlbumArt(getContext(), musicFile.getAlbumCover());
            Bitmap bit = MusicScannerUtil.getAlbumArt(getContext(), musicFile.getArtistCover());
            ivPlayer.setImageBitmap(null);
            if (albumCover != null) {
                ivPlayer.setImageBitmap(albumCover);
            } else {
                if (bit != null) {
                    ivPlayer.setImageBitmap(bit);
                }
            }
        }
    }

    private String formatTime(long millis) {
        return String.format("%02d:%02d",
                TimeUnit.MILLISECONDS.toMinutes(millis),
                TimeUnit.MILLISECONDS.toSeconds(millis) % 60);
    }
    // endregion


    @Override
    public void onPlaybackStateChanged(boolean isPlaying) {
        btnPlayType();
    }

    @Override
    public void onPlaybackStateChanged(int state) {
        updatePlayerState();
        if (state == Player.STATE_ENDED) {
            playerManager.playNext();
        }
        // 控制进度更新
        if (playerManager.isPlaying()) {
            playerManager.startProgressUpdates();
        } else {
            playerManager.stopProgressUpdates();
        }
    }

    @Override
    public void onProgressUpdated(long position, long duration) {
        // 同步其他页面的进度更新（如通知栏）
        progressBar.setProgress((int) (position / 1000));
        currentTime.setText(formatTime(position));
    }

    @Override
    public void onTrackChanged(MusicFile currentTrack) {
        // 更新曲目信息显示

        // 重置进度显示
        progressBar.setProgress(0);
        currentTime.setText("00:00");
        totalTime.setText(formatTime(currentTrack.getDuration()));
    }
    // endregion

    // 辅助方法：更新所有显示状态
    private void updatePlayerState() {
        btnPlayType();
        updateProgressDisplay();
    }

    private void btnPlayType() {
        btnPlay.setImageResource(
                playerManager.isPlaying() ? R.drawable.stop : R.drawable.bofang
        );
    }
}